package cn.qyl.joha.dao;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class BaseDao {
	private static SqlSessionFactory factory;
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); 
	
	static{
		try{
			InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
			factory = new SqlSessionFactoryBuilder().build(is);
			
		}catch(IOException e){
			e.printStackTrace();
			
		}
		
	}
	
	
	//获取Session
	public SqlSession getSqlSession(){
		
		SqlSession sqlSession = threadLocal.get();
		if(sqlSession == null){
			//通过sqlSessionFactory获取Session
			sqlSession = factory.openSession();
		}
		//再把sqlSession存储到threadLocal中
		threadLocal.set(sqlSession);
		return sqlSession;
		
	}
	
	//释放SqlSession
	public void closeSqlSession(){
		SqlSession sqlSession = threadLocal.get();
		
		if(sqlSession !=null){
			//关闭SqlSession
			sqlSession.close();
		}
		//清空threadLocal
		threadLocal.remove();
	}

}
